<?php

namespace App;

use App\Models\Permissions;
use App\Models\Roles;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;

    /**
     *
     * 用户----角色----权限
     * 用户 权限 通过角色获取
     */
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'username', 'email', 'password',
    ];


    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected $table = 'users';

    public function manyPermissions()
    {
        return $this->belongsToMany(Permissions::class,'user_permissions','user_id','permission_id');
    }
    public function manyRoles()
    {
        return $this->belongsToMany(Roles::class,'role_users','user_id','role_id');
    }

    /****************************************
     * 封装一个方法方便使用
     * 1. 需要的权限
     * 2. 遍历当期那用户拥有的所有角色
     * 3. 再通过角色判断是否有当前需要的权限
     ****************************************/
    public function hasPermission($permission)
    {
        foreach ($this->manyRoles as $role) {
            if($role->manyPermissions->where('slug',$permission)->first())
            {
                return true;
            }
        }

        return false;
    }

    /**
     * @return \Illuminate\Database\Eloquent\Collection
     * 通过角色去获取权限
     */
    public function allPermissions()
    {
        return $this->manyRoles()->with('manyPermissions')->get()->pluck('manyPermissions')->flatten();

    }

    /**
     * @return array
     * 获取权限菜单
     */
    public function getMenus()
    {

        $result=[];
        $menus=$this->manyRoles()->with('manyMenus')->get()->pluck('manyMenus')->flatten()->toArray();
        //$menus=$this->manyRoles()->with('manyMenus')->get()->pluck('manyMenus')->flatten()->merge($this->manyMenus)->toArray();
        //$menus=$this->manyRoles()->with('manyMenus')->get()->toArray();
        foreach ($menus as $menu)
        {
            $result[$menu['id']]=$menu;
        }
        return $result;

    }

    /**
     * @param $role
     * @return bool
     * 是否是角色
     */
    public function isRole($role)
    {
        return $this->manyRoles()->get()->pluck('slug')->contains($role);
    }

    /**
     * 是否是超级管理员
     */
    public function isRoot()
    {
        return $this->isRole('root');
    }
}
